<template>
  <div class="task-manage-page">
    <PageHeader title="任务管理" backPath="/dawn/dashboard/root"></PageHeader>

    <!-- 任务列表 -->
    <div class="task-list-title">任务列表</div>
    <div class="task-list">
      <div class="batch-bar">
        <div class="select-all-box">
          <Checkbox :model-value="isAllSelected" @update:model-value="toggleSelectAll" class="select-all-checkbox" />
          <span class="select-all-label">全选</span>
        </div>
        <div class="batch-actions">
          <button class="start-selected-btn batch-btn" :disabled="!selectedTasks.length" @click="batchUpdateTaskStatus(true)">启动选中</button>
          <button class="pause-selected-btn batch-btn" :disabled="!selectedTasks.length" @click="batchUpdateTaskStatus(false)">暂停选中</button>
          <button class="delete-selected-btn batch-btn" :disabled="!selectedTasks.length" @click="deleteSelectedTasks">删除选中</button>
        </div>
      </div>
      <CheckboxGroup v-model="selectedTasks">
        <div class="task-item" v-for="task in taskList" :key="task.id">
          <div class="task-header">
            <div class="checkbox-row">
              <Checkbox :name="task.id" />
            </div>
            <div class="task-status">
              <span :class="['status-badge', task.status ? 'status-running' : 'status-paused']">
                {{ task.status ? '运行中' : '已暂停' }}
              </span>
            </div>
          </div>
          <div class="task-content">
            <div class="task-row">
              <span class="task-label">任务名称</span>
              <span class="task-value">{{ task.func }}</span>
            </div>
            <div class="task-row">
              <span class="task-label">创建者</span>
              <span class="task-value task-creator">{{ task.creatorName }} ({{ task.creatorId }}) - {{ task.username }}</span>
            </div>
            <div class="task-row">
              <span class="task-label">Cron表达式</span>
              <span class="task-value">{{ task.cron }}</span>
            </div>
            <div class="task-row">
              <span class="task-label">延迟类型</span>
              <span class="task-value">{{ task.delayType }}</span>
            </div>
            <div class="task-row" v-if="task.delayTime">
              <span class="task-label">延迟时间</span>
              <span class="task-value">{{ task.delayTime }}秒</span>
            </div>
            <div class="task-row" v-if="task.jitterTime">
              <span class="task-label">间隔时间</span>
              <span class="task-value">{{ task.jitterTime }}秒</span>
            </div>
            <div class="task-row">
              <span class="task-label">创建时间</span>
              <span class="task-value">{{ task.createTime }}</span>
            </div>
            <div class="task-row">
              <span class="task-label">下次执行时间</span>
              <span class="task-value">{{ task.nextTime }}</span>
            </div>
            
            <div class="task-actions">
              <van-button 
                size="normal" 
                :type="task.status ? 'warning' : 'success'"
                @click="toggleTask(task)"
                class="action-btn"
              >
                {{ task.status ? '暂停' : '启动' }}
              </van-button>
              <van-button 
                size="normal" 
                type="danger" 
                @click="deleteTask(task)"
                class="action-btn"
              >
                删除
              </van-button>
            </div>
          </div>
        </div>
      </CheckboxGroup>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <van-pagination
        v-model="currentPage"
        :total-items="total"
        :items-per-page="pageSize"
        mode="simple"
        @change="fetchTaskList"
      />
      <div class="pagination-info">
        当前：{{ currentPage }} / {{ totalPages }}页 总数：{{ total }}条
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { showToast, Field as VanField, Button as VanButton, Tag as VanTag, Pagination as VanPagination, Checkbox, CheckboxGroup } from 'vant'
import PageHeader from '@/Pages/compontents/PageHeader.vue'
import request from '@/utils/request';
import apiUrls  from '@/config/apiUrls'; 
import { getNextExecutionTime } from '@/utils/utils';

const taskList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
const selectedTasks = ref([])

const isAllSelected = computed(() => taskList.value.length > 0 && selectedTasks.value.length === taskList.value.length)

function toggleSelectAll(val) {
  if (val) {
    selectedTasks.value = taskList.value.map(task => task.id)
  } else {
    selectedTasks.value = []
  }
}

const fetchTaskList = async () => {
  try {
    const response = await request.get(apiUrls.root.getAllTaskDetails, {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })
    
    if (response.code === 200) {
      taskList.value = response.data.list.map(task => ({
        id: task.id,
        func: task.name,
        creatorName: task.zhjy_user.dawn_zhjyIdName,
        creatorId: task.zhjy_user.dawn_zhjyIStudentId,
        username: task.user.dawn_name,
        cron: task.cron_expression,
        timeType: task.time_type,
        delayTime: task.delay_time,
        jitterTime: task.jitter_time,
        createTime: new Date(task.created_at).toLocaleString(),
        nextTime: getNextExecutionTime(task.cron_expression),
        delayType: getTime_type(task.time_type),
        status: task.is_active // 直接使用布尔值
      }))
      total.value = response.data.total
    } else {
      showToast(response.message || '获取任务列表失败')
    }
  } catch (error) {
    showToast('获取任务列表失败')
    console.error('获取任务列表失败:', error)
  }
}

const getTime_type = (timeType) => {
  const typeMap = {
    'cron_expression': '不延时',
    'delay_time': '固定延迟时间',
    'jitter_time': '间隔时间'
  }
  return typeMap[timeType] || timeType
}

const toggleTask = async (task) => {
  try {
    const response = await request.post(apiUrls.root.updateTaskDetails, {
      ids: [task.id],
      is_active: !task.status
    })
    
    if (response.code === 200) {
      task.status = !task.status
      showToast(task.status ? '任务已启动' : '任务已暂停')
    } else {
      showToast(response.message || '操作失败')
    }
  } catch (error) {
    showToast('操作失败')
    console.error('更新任务状态失败:', error)
  }
}

const getStatusText = (status) => {
  return status ? '运行中' : '已暂停'
}

const deleteTask = async (task) => {
  // 这里应请求后端接口删除任务
  try {
    const response = await request.delete(apiUrls.root.deleteTaskDetails, {
      data: {
        ids: [task.id],
      }
    })
    if (response.code === 200) {
      // 移除已删除项
      showToast('批量删除成功')
      fetchTaskList()

    } else {
      showToast(response.message || '批量删除失败')
    }
  } catch (error) {
    console.log(error);
    
    showToast('批量删除失败')
  }
}

async function deleteSelectedTasks() {
  if (!selectedTasks.value.length) return
  try {
    const response = await request.delete(apiUrls.root.deleteTaskDetails, {
      data: {
        ids: selectedTasks.value,
      }
    })
    if (response.code === 200) {
      // 移除已删除项
      showToast('批量删除成功')
      fetchTaskList()
    } else {
      showToast(response.message || '批量删除失败')
    }
  } catch (error) {
    console.log(error);
    
    showToast('批量删除失败')
  }
}

async function batchUpdateTaskStatus(isActive) {
  if (!selectedTasks.value.length) return
  try {
    const response = await request.post(apiUrls.root.updateTaskDetails, {
      ids: selectedTasks.value,
      is_active: isActive
    })
    if (response.code === 200) {
      showToast(isActive ? '批量启动成功' : '批量暂停成功')
      fetchTaskList()
    } else {
      showToast(response.message || (isActive ? '批量启动失败' : '批量暂停失败'))
    }
  } catch (error) {
    console.log(error)
    showToast(isActive ? '批量启动失败' : '批量暂停失败')
  }
}

onMounted(() => {
  fetchTaskList()
})
</script>

<style scoped>
.task-manage-page {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 24px 16px 40px 16px;
  background: #f7f8fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.task-list-title {
  margin: 0 0 16px 0;
  color: #1e9fff;
  font-weight: 600;
  font-size: 18px;
}

.task-list {
  width: 100%;
}

.batch-bar {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 18px;
}

.select-all-box {
  display: flex;
  align-items: center;
  background: #f7fafd;
  border-radius: 8px;
  padding: 0 16px;
  height: 44px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}

.batch-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.select-all-checkbox {
  margin-right: 8px;
  transform: scale(1.2);
}

.select-all-label {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.batch-btn {
  flex: 1;
  min-width: 90px;
  padding: 10px 0;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  border: none;
  transition: background 0.2s, box-shadow 0.2s;
}

.start-selected-btn {
  background: #4fc669;
  color: #fff;
}

.start-selected-btn:disabled {
  background: #d2f2c2;
  color: #fff;
}

.pause-selected-btn {
  background: #f9ae3d;
  color: #fff;
}

.pause-selected-btn:disabled {
  background: #ffe2b6;
  color: #fff;
}

.delete-selected-btn {
  background: #f56c6c;
  color: #fff;
}

.delete-selected-btn:disabled {
  background: #fbc4c4;
  color: #fff;
}

.batch-btn:not(:disabled):hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.10);
  filter: brightness(1.08);
}

.task-item {
  position: relative;
  background: #fff;
  border-radius: 12px;
  margin-bottom: 16px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.checkbox-row {
  display: flex;
  align-items: center;
}

.task-status {
  display: flex;
  align-items: center;
}

.task-content {
  margin-top: 8px;
}

.task-row {
  display: flex;
  flex-direction: column;
  margin-bottom: 12px;
}

.task-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
  font-weight: 500;
}

.task-value {
  color: #333;
  font-size: 15px;
  word-break: break-word;
}

.task-creator {
  word-break: break-all;
}

.status-badge {
  padding: 6px 10px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
}

.status-running {
  background-color: #4caf50;
  color: #fff;
}

.status-paused {
  background-color: #f44336;
  color: #fff;
}

.task-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

.action-btn {
  flex: 1;
  height: 40px;
  border-radius: 8px;
  font-size: 15px;
}

.pagination-wrapper {
  margin-top: 20px;
  background: #fff;
  border-radius: 12px;
  padding: 16px 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  text-align: center;
}

.pagination-info {
  margin-top: 12px;
  color: #666;
  font-size: 14px;
}

/* 响应式样式 */
@media screen and (min-width: 768px) {
  .batch-bar {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
  
  .select-all-box {
    margin-right: 0;
    width: auto;
  }
  
  .batch-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  .task-row {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  
  .task-label {
    margin-bottom: 0;
    width: 100px;
    flex-shrink: 0;
  }
  
  .task-value {
    flex: 1;
    text-align: right;
  }
}
</style>